package cn._2dland.sakushi.servlet;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;

import cn._2dland.sakushi.jdo.PMFactory;
import cn._2dland.sakushi.jdo.Question;

/**
 * picker servlet
 * 负责定期提取未处理的消息
 * 
 * @author deadblue
 */
public class FanfouPickerServlet extends HttpServlet {
	private static final long serialVersionUID = -1216330337182667575L;

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		PersistenceManager pm = PMFactory.getPMFInstance().getPersistenceManager();
		try {
			// 查询出所有未处理的消息
			Query query = pm.newQuery(Question.class);
			query.setFilter("status == 0");
			List<Question> qs = (List<Question>)query.execute();

			if(!qs.isEmpty()) {
				// 获取消息队列
				Queue queue = QueueFactory.getQueue("sakushi-queue");

				// 将未处理的消息加入到队列
				for(Question q : qs) {
					TaskOptions task = TaskOptions.Builder.withUrl("/fanfouSakushi");
					task.method(TaskOptions.Method.POST);
					task.param("status_id", q.getId());
					queue.add(task);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pm.close();
		}
	}
}
